package chat

import (
	"context"

	"github.com/alibabacloud-go/tea/tea"
)

// https://beta.openai.com/docs/api-reference/completions/create
func (r *ChatRobot) SendMessage(ctx context.Context, in *SendMessageRequest) (
	*SendMessageResponse, error) {
	resp := NewSendMessageResponse()
	err := r.client.
		Post("completions").
		Body(in).
		Do(ctx).
		Into(resp)
	if err != nil {
		return nil, err
	}
	return resp, nil
}

func NewSendMessageRequest(prompt string) *SendMessageRequest {
	return &SendMessageRequest{
		Model:       "text-davinci-003",
		Prompt:      prompt,
		MaxTokens:   1000,
		Temperature: 0,
	}
}

//	{
//		"model": "text-davinci-003",
//		"prompt": "Say this is a test",
//		"max_tokens": 7,
//		"temperature": 0,
//		"top_p": 1,
//		"n": 1,
//		"stream": false,
//		"logprobs": null,
//		"stop": "\n"
//	}
type SendMessageRequest struct {
	Model       string `json:"model"`
	Prompt      string `json:"prompt"`
	MaxTokens   int64  `json:"max_tokens"`
	Temperature int64  `json:"temperature"`
}

func (r *SendMessageRequest) String() string {
	return tea.Prettify(r)
}

func NewSendMessageResponse() *SendMessageResponse {
	return &SendMessageResponse{
		Choices: []*ChoiceItem{},
		Usage:   &SendMessageUsage{},
	}
}

//	{
//		"id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
//		"object": "text_completion",
//		"created": 1589478378,
//		"model": "text-davinci-003",
//		"choices": [
//		  {
//			"text": "\n\nThis is indeed a test",
//			"index": 0,
//			"logprobs": null,
//			"finish_reason": "length"
//		  }
//		],
//		"usage": {
//		  "prompt_tokens": 5,
//		  "completion_tokens": 7,
//		  "total_tokens": 12
//		}
//	}
type SendMessageResponse struct {
	Id      string            `json:"id"`
	Object  string            `json:"object"`
	Created int64             `json:"created"`
	Model   string            `json:"model"`
	Choices []*ChoiceItem     `json:"choices"`
	Usage   *SendMessageUsage `json:"usage"`
}

func (r *SendMessageResponse) String() string {
	return tea.Prettify(r)
}

type ChoiceItem struct {
	Text         string `json:"text"`
	Index        int    `json:"index"`
	FinishReason string `json:"finish_reason"`
}

type SendMessageUsage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}
